import socket

if __name__ == '__main__':
    # 1.创建tcp服务端套接字

    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 2.绑定端口号

    tcp_server_socket.bind(("", 9091))
    # 3.设置监听

    tcp_server_socket.listen(128)
    # 4.等待接收客户端的连接请求

    new_client, ip_port = tcp_server_socket.accept()

    print("端口号",ip_port)
    # 5.接收客户端数据
    # 收发信息都使用新的套接字
    while True:
        while True:
            recv_data = new_client.recv(1024)
            # 对二进制数据进行解码变成字符串
            recv_content = recv_data.decode("utf-8")
        if recv_content == "close":
            break
        else:
            print(f"接收客户端的数据为:{recv_content}")
        data_res = input("服务器")
        if data_res == "close":
            # 对字符串进行编码
            send_data = data_res.encode("utf-8")
            new_client.send(send_data)
            break
        else:
            new_client.send(data_res.encode("utf-8"))
    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    tcp_server_socket.close()